package org.dallasrowing.model.dao.sqlmap;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.dallasrowing.model.Rower;
import org.dallasrowing.model.dao.DAOException;
import org.dallasrowing.model.dao.RowersDAO;

import com.ibatis.sqlmap.client.SqlMapClient;

public class SqlMapRowersDAO implements RowersDAO {

	private static final String ROWERS_BY_ENTRY_DATE = "Rowers.listRowersByLogBookEntry";
	private static final String ROWERS_BY_SEARCH_NAME = "Rowers.searchRowersByName";
	private static final String ROWER_CREATE = "Rowers.insert";
	private static final String ROWER_UPDATE = "Rowers.update";
	
	private SqlMapClient sqlMap;

	public SqlMapRowersDAO(SqlMapClient sqlMap) {
		this.sqlMap = sqlMap;
	}

	@SuppressWarnings( "unchecked" )
	public List<Rower> listRowersByLogBookEntry(Date entryStartDate) throws DAOException
	{
		try {
			return sqlMap.queryForList(ROWERS_BY_ENTRY_DATE, entryStartDate);
		} catch (SQLException e) {
			throw new DAOException( e );
		}
	}

	@SuppressWarnings( "unchecked" )
	public List<Rower> searchRowersByName(String searchName, boolean onlyActive) throws DAOException {
		try {
			List list = sqlMap.queryForList(ROWERS_BY_SEARCH_NAME, searchName);
			if (onlyActive)
				list = filterInactive(list);
			return list;
		} catch (SQLException e) {
			throw new DAOException( e );
		}
	}

	private ArrayList<Rower> filterInactive(List<Rower> list) {
		ArrayList<Rower> result = new ArrayList<Rower>();
		for (Rower r : list)
		{
			if (r.getActive())
				result.add(r);
		}
		return result;
	}

	public void createNewRower(Rower newRower) throws DAOException {
		try {
			if ( searchRowersByName(newRower.getName().trim(), true).size() >0 )
			{
				throw new DAOException( "Rower already exists", null);
			}
			sqlMap.insert(ROWER_CREATE, newRower);
		} catch (SQLException e) {
			throw new DAOException( e );
		}
	}

	public void updateRower(Rower rower) throws DAOException {
		try {
			sqlMap.update(ROWER_UPDATE, rower);
		} catch (SQLException e) {
			throw new DAOException(e);
		}
	}
	
	

}
